﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace olierFrm.Extensions.Html
{
    public static class HtmlExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="html"></param>
        /// <param name="htmlString"></param>
        /// <param name="length">截断长度</param>
        /// <param name="ext">结尾字符</param>
        /// <returns></returns>
        public static string NoHTML(this System.Web.Mvc.HtmlHelper html, object htmlString, int length = 0, string ext = "")
        {
            if (htmlString == null || htmlString.ToString().Trim().Length == 0) return "";
            var htmlS = htmlString.ToString();

            //删除脚本 
            htmlS = Regex.Replace(htmlS, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML 
            htmlS = Regex.Replace(htmlS, @"<br>", "$br$", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"$br$", "<br>", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"([\r\n])[\s]+", "<br>", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"-->", "", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"<!--.*", "", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            // Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            htmlS = Regex.Replace(htmlS, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            htmlS.Replace("<", "");
            htmlS.Replace(">", "");
            htmlS.Replace("\r\n", "");
            if (length != 0)
            {
                var oldLen = htmlS.Length;
                var len = (htmlS.Length > length ? length : htmlS.Length);
                htmlS = htmlS.Substring(0, len);
                if (oldLen > len) htmlS += ext;
            }

            return htmlS;
        }
    }
}
